package com.wmyg.antifake.controller;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.wmyg.antifake.bean.Brand;
import com.wmyg.antifake.bean.Factory;
import com.wmyg.antifake.bean.Picture;
import com.wmyg.antifake.bean.Product;
import com.wmyg.antifake.service.BrandService;
import com.wmyg.antifake.service.FactoryService;
import com.wmyg.antifake.service.PictureService;
import com.wmyg.antifake.service.ProductService;
import com.wmyg.antifake.utils.FileUtil;
import com.wmyg.antifake.utils.ReplayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private FactoryService factoryService;
    @Autowired
    private PictureService pictureService;

    @Value("${files.uploadFolder}")
    private String uploadBasePath;
    @Value("${files.staticAccessPath}")
    private String staticAccessPath;

    @RequestMapping(value = "toAdd")
    public ModelAndView toAdd(ModelAndView mv) {
        List<Brand> brands = brandService.findAll();
        List<Factory> factories = factoryService.findAll();
        mv.setViewName("product/add");
        mv.addObject("product",new Product());
        mv.addObject("brands",brands);
        mv.addObject("factories",factories);
        mv.addObject("staticAccessPath",staticAccessPath);
        return mv;
    }

    @RequestMapping(value = "toUpdate")
    public ModelAndView toUpdate(ModelAndView mv,String productId) {
        List<Brand> brands = brandService.findAll();
        List<Factory> factories = factoryService.findAll();
        Product product = productService.selectById(productId);
        mv.setViewName("product/add");
        mv.addObject("product",product);
        mv.addObject("brands",brands);
        mv.addObject("factories",factories);
        mv.addObject("staticAccessPath",staticAccessPath);
        return mv;
    }

    @PostMapping("/login")
    public ModelAndView login(HttpServletRequest request, ModelAndView mv,
                              @Valid Product product, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            mv.addObject("error",bindingResult.getFieldError().getDefaultMessage());
            mv.setViewName("loginb");
            return mv;
        }

        mv.addObject("loginProduct","dd");
        mv.setViewName("product/list");
        return mv;
    }

    @RequestMapping(value = "/view")
    public ModelAndView view(ModelAndView mv,String productId) {
        mv.setViewName("product/view");
        Product product = productService.selectById(productId);

        mv.addObject("staticAccessPath",staticAccessPath);
        mv.addObject("product",product);
        return mv;
    }


    @RequestMapping(method = RequestMethod.POST,value = "/add")
    public ModelAndView add(ModelAndView mv,Product product){

        String productId = product.getProductId();
        Product product1 = productService.selectById(productId);
        if(StringUtil.isNotEmpty(product1.getProductId())){
            mv.addObject("error","商品编号已经存在了！");
            mv.setViewName("product/add");
            List<Brand> brands = brandService.findAll();
            List<Factory> factories = factoryService.findAll();
            mv.addObject("brands",brands);
            mv.addObject("factories",factories);
            mv.addObject("staticAccessPath",staticAccessPath);
            return mv;
        }
        mv.setViewName("success");
        productService.insert(product);

        return mv;
    }

    @RequestMapping(method = RequestMethod.POST,value = "/update")
    public ModelAndView update(ModelAndView mv,Product product){
        productService.update(product);
        mv.setViewName("success");
        return mv;
    }

    /**
     * 上传图片
     * @param requests
     * @param response
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> upload(MultipartHttpServletRequest requests, HttpServletResponse response){
        //上传路径
        String filePath =  "/static/pic/product/";
        Map<String,Object> baseResult = FileUtil.upload(requests,filePath,staticAccessPath,uploadBasePath);
        return baseResult;
    }

   @RequestMapping("/findAll")
   public ReplayUtils findAll( @RequestParam(required = false) String pName,
                              @RequestParam Integer pageSize,
                              @RequestParam Integer pageIndex) {
       PageInfo<Product> pageInfo = productService.findAll(pName,pageIndex,pageSize);
       //mv.addObject("staticAccessPath",staticAccessPath);
       return new ReplayUtils(pageInfo.getTotal(), pageInfo.getList(),0);
   }

    @RequestMapping("/toFindAll")
    public ModelAndView toFindAll( ModelAndView mv) {
        mv.addObject("staticAccessPath",staticAccessPath);
        mv.setViewName("product/productList");
        return mv;
    }

    @RequestMapping(method = RequestMethod.GET,value = "/del")
    public ModelAndView delete(ModelAndView mv, @RequestParam(required = true) String productId){
        productService.delete(productId);
        mv.setViewName("success");
        return mv;
    }


    @RequestMapping("/findAllProduct")
    @ResponseBody
    public   List<Product>  findAllProduct( ) {
        List<Product> list = productService.findAllProduct();
        return list;
    }

    @RequestMapping("/findQrCodeNum")
    @ResponseBody
    public   Map<String,BigDecimal> findQrCodeNum(String productId) {
       if(StringUtils.isEmpty(productId)){
           return null;
       }
        Map<String,BigDecimal> map = productService.findQrCodeNum(Long.parseLong(productId));
        return map;
    }


    @RequestMapping("/deletePic")
    @ResponseBody
    public   int  deletePic(String picId) {
        if(StringUtils.isEmpty(picId)){
            return 0;
        }
        Picture picture =  pictureService.selectPrimaryId(Integer.parseInt(picId));
        if(picture==null){
            return 0;
        }
        String url=uploadBasePath+picture.getPicUrl();
        url = url.replaceAll("\\\\", "/");
        int isDelete = FileUtil.deletePic(url);
        if(isDelete==0){
            return 0;
        }
        return  pictureService.deletePrimaryId(Integer.parseInt(picId));
    }
}
